package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    //客户端
    DatagramSocket socket = null;
    //我们这里的客户端的构造，我们需要传入服务器的IP和端口号
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket = new DatagramSocket();//这里我们不进行传入端口号，因为端口号可能会产生冲突，所以让其随机的寻找
    }

    private void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            // 1、从控制台进行输入
            System.out.println("请输入要发送的内容：");
            String request = scanner.next();

            // 2、把客户端的内容发送给服务器，服务器进行处理
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);

            // 3、处理之后把其返回，并进行打印
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            // 4、对其返回结果进行打印
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        //这里的端口号，我们需要和服务端的 端口号一致
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
